/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UserManager;

import DBManager.DBConnection;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 *
 * @author TigerBoy
 */
public class CreditCardManager {
    
    
    private void creditCardManagerLogs(String functionName,String status,String input)
    {
    
        String path = "C:/Foobar_Logs/creditCardLogs.txt";
        
        try
        {
            File file = new File(path);
            FileWriter fw = new FileWriter( file , true);
            BufferedWriter bw = new BufferedWriter(fw);
           
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            java.util.Date date = new java.util.Date();
            String currentDate = dateFormat.format(date);
            
            bw.write("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); bw.newLine();
            bw.write("Function:" + functionName + " has " + status + ""); bw.newLine();
            bw.write(input); bw.newLine();
            bw.write("Excecution Date and Time: " + currentDate); bw.newLine();
            
            bw.close();
            
        }
        catch (Exception e)
        {
            
            System.out.println(e);
            System.out.println("Writing to the text file: \n" + path + " has failed");
            System.out.println("Please Check if Diskspace is full");
            
        }
    
    }
    
    //Uses Luhn's algorithm to check
    public boolean verifyCardNumber(CreditCard card){
        
        String cardnumber = card.getCreditNumber();
        
        if(card.getCreditNumber() == null || card.getCreditName() == null)
               return false;
        
        int sum =0;
        
        boolean multiChecker=false;
        
        for(int i = cardnumber.length()-1;i>=0;i--)
        {
            int n = Integer.parseInt(cardnumber.substring(i, i + 1));
            
            if(multiChecker)
            {
            
                n *= 2;
                if (n > 9)
                {
                     n = (n % 10) + 1;
                }
            
            }
            
            sum += n;
            multiChecker = !multiChecker;
            
        
        }
        
        Calendar cal = Calendar.getInstance();
        
        if(sum % 10 == 0 && 
                Calendar.getInstance().get(Calendar.YEAR)<=card.getCreditYear()&& 
                cardnumber.length()==16 &&
               (cardnumber.charAt(0) == '4' || cardnumber.charAt(0) == '5')
                )
        {   
            if(Calendar.getInstance().get(Calendar.YEAR)==card.getCreditYear() && 
                    Calendar.getInstance().get(Calendar.MONTH)<card.getCreditMonth()
                    )
            {
                return true;
            }
            else
            if( Calendar.getInstance().get(Calendar.YEAR)<card.getCreditYear() )
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
        
    }
    
    // Needs credit card number, call viewUser function first =)
    public boolean viewCard(CreditCard newCard)
    {
        boolean result = false;
        
        try{
            //get connection
            DBConnection db = new DBConnection();
            Connection conn = db.getConnection();
            
            //Construct SQL Query
            PreparedStatement pstmt = conn.prepareStatement("Select * FROM creditcard WHERE creditNumber=?");
            
            //append values for the parameters
            int i=1;
            
            pstmt.setString(i++, newCard.getCreditNumber());
            
            //execute SQL statement
            ResultSet rst = pstmt.executeQuery();
            
            
            while(rst.next())
            {
                
                newCard.setCreditName(rst.getString("creditName"));
                newCard.setCreditNumber(rst.getString("creditNumber"));
                newCard.setCreditYear(rst.getInt("creditYear"));
                newCard.setCreditMonth(rst.getInt("creditMonth"));
                newCard.setCreditCompany(rst.getString("creditCompany"));
                newCard.setAddressBillNumber(rst.getString("addressBillNumber"));
                newCard.setAddressBillStreet(rst.getString("addressBillStreet"));
                newCard.setAddressBillSubdivision(rst.getString("addressBillSubdivision"));
                newCard.setAddressBillCity(rst.getString("addressBillCity"));
                newCard.setAddressBillPostal(rst.getString("addressBillPostal"));
                newCard.setAddressBillCountry(rst.getString("addressBillCountry"));
                newCard.setDateCreated(rst.getString("dateCreated"));
                result = true;
            }
            
            creditCardManagerLogs("viewCard","excecuted",newCard.getCreditNumber());
            // newCard.getCreditNumber().substring(0, newCard.getCreditNumber().length()-8) + "xxxxxxxx"
            pstmt.close();
            
        }
        catch(SQLException ex)
        {
        
            creditCardManagerLogs("viewCard","failed to excecute", newCard.getCreditNumber());
            System.out.println("viewCard() has failed to execute");
            
        }   
    
        return result;
    }
    
    public boolean changeCreditCard(CreditCard newCard,String username)
    {
        boolean result = false;
        
        if(username != null && 
                newCard.getAddressBillCity() != null &&
                newCard.getAddressBillCountry() != null &&
                newCard.getAddressBillNumber() != null &&
                newCard.getAddressBillPostal() != null &&
                newCard.getAddressBillStreet() != null &&
                newCard.getAddressBillSubdivision() != null &&
                newCard.getCreditName() != null &&
                newCard.getCreditNumber() != null &&
                newCard.getCreditCompany() !=null
                )
        {
            try{
                DBConnection db = new DBConnection();
                Connection conn = db.getConnection();
                Connection conn0 = db.getConnection();

                conn.setAutoCommit(false);

                PreparedStatement pstmt1 =
                    conn.prepareStatement("UPDATE user SET creditNumber=? WHERE username=?");

                PreparedStatement pstmt2 =
                    conn.prepareStatement("INSERT "
                                    + "INTO creditcard(creditName,creditNumber,creditYear,creditMonth,creditCompany,"
                                    + "addressBillNumber,addressBillStreet,addressBillSubdivision,addressBillCity,addressBillPostal,addressBillCountry,dateCreated)"
                                    + "values(?,?,?,?,?,?,?,?,?,?,?,?)");

                PreparedStatement pstmt0 = conn.prepareStatement("SELECT creditNumber FROM user WHERE username=?");


                int i=1;
                pstmt0.setString(i++, username);

                ResultSet rst = pstmt1.executeQuery();

                String tempcard = "";

                while(rst.next())
                {
                    tempcard = rst.getString("creditNumber");
                }

                // for log purposes
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                java.util.Date date = new java.util.Date();
                String currentDate = dateFormat.format(date);

                i=1;
                pstmt1.setString(i++, newCard.getCreditNumber());
                pstmt1.setString(i++, username);

                /* for credit card*/
                i=1;
                pstmt2.setString(i++, newCard.getCreditName());
                pstmt2.setString(i++, newCard.getCreditNumber());
                pstmt2.setString(i++, String.valueOf(newCard.getCreditYear()));
                pstmt2.setString(i++, String.valueOf(newCard.getCreditMonth()));
                pstmt2.setString(i++, newCard.getCreditCompany());
                pstmt2.setString(i++, newCard.getAddressBillNumber());
                pstmt2.setString(i++, newCard.getAddressBillStreet());
                pstmt2.setString(i++, newCard.getAddressBillSubdivision());
                pstmt2.setString(i++, newCard.getAddressBillCity());
                pstmt2.setString(i++, newCard.getAddressBillPostal());
                pstmt2.setString(i++, newCard.getAddressBillCountry());
                pstmt2.setString(i++, currentDate);

                String input;

                if(!verifyCardNumber(newCard))
                {
                    pstmt1.close();
                    pstmt2.close();
                    input = "Invalid Card Number from" + username +" using " + newCard.getCreditNumber() + " with year " + newCard.getCreditYear() + " and month " + newCard.getCreditMonth();
                    creditCardManagerLogs("changeCard","excecuted", input );

                    return result;
                }

                //execute SQL statement
                pstmt1.executeUpdate();
                pstmt2.executeUpdate();

                conn.commit();

                pstmt1.close();
                pstmt2.close();
                result = true;

                input = username + " is change from " + tempcard + "to" + newCard.getCreditNumber();

                creditCardManagerLogs("changeCard","excecuted",input);

            }catch(SQLException ex)
            {

                System.out.println("changeCreditCard() has failed to execute");

                creditCardManagerLogs("changeCard","failed to excecute", username);

            }
        }
            
        return result;
            
        
        
    }
    
    
}
